import time

import uiautomation as auto
from game import zz_game_shengdian, zz_game, zz_player_data
from pynput.keyboard import Key
from zz import zz_code, zz_dingtalk, zz_str
import sys
import traceback

auto.uiautomation.SetGlobalSearchTimeout(3)  # 设置全局搜索超时 5

window = auto.PaneControl(searchDepth=1, ClassName='地下城与勇士')  # search 2 times
# 控制的应用窗口前置
# window.SetTopmost(True)
window.Click(50, 100)

game = zz_game_shengdian.Game(window)


def play1(player_index):
    game.set_player_index(player_index)
    state = game.get_player_config("state")
    step_go = True
    if state is None:
        step_go = False
    if state == 1:
        game.log_msg(f"{player_index}角色已完成任务")
        return False

    game.set_player_config("time_begin", zz_code.date_tostring(), True)
    game.set_player_config("state", 0, True)

    if not step_go:
        select_ok = game.player_select(game.player_index)
        if not select_ok:
            return False
        game.go()

    ok = False
    count = 1
    while True:
        ok = game.handle_main(count % 6 == 0)
        if not ok:
            break

        if game.game_end():
            game.log_msg("已挑战完成")
            game.click_key(Key.f12)
            time.sleep(2)
            break
        game.log_msg("再次挑战")
        game.game_f10()

        count += 1

    if ok:
        time_begin = zz_code.date_from_str(game.get_player_config("time_begin"))
        time_end = zz_code.date_now()
        time_span = time_end - time_begin
        game.set_player_config("time_span", time_span.seconds)
        game.set_player_config("state", 1)

        time_m = int(time_span.seconds / 60)
        title = f"DNF-角色{player_index}完成[{time_m}] \n\n"
        msg = f"**DNF-角色{player_index}完成** \n\n运行总时长：{time_m}分"
        zz_dingtalk.send_markdown(msg, title)

    return ok


def main(account_index):
    game.log_msg(f"帐号：{account_index}")
    zz_game.config_path_set(f"./game_config_{account_index}.json")

    player_data = zz_player_data.to_list(f'./player_data_{account_index}.json')
    game.set_player_data(player_data)

    while True:
        player_index = -1
        r = zz_game.config_to_return()
        for i in range(4):
            player_key = f"player_{i}"
            if not r.exists(player_key):
                player_index = i
                break
            if r.exists(player_key) and r.get_data(player_key)['state'] == 0:
                player_index = i
                break
        if player_index == -1:
            game.log_msg("全部角色已做完任务")
            break
        ok = play1(player_index)
        if not ok:
            raise ValueError("运行异常")
            break


if __name__ == '__main__':
    arguments = sys.argv[1:]

    index = 1
    if zz_str.has_any_text(arguments[0]):
        index = int(arguments[0])
    try:
        main(index)
    except Exception as ex:
        traceback.print_exc()
        game.log_msg(ex)
        # 异常导出，发钉钉通知
        title = "DNF-异常退出"
        msg = f"{title} \n\n {ex}"
        zz_dingtalk.send_markdown(msg, title)
